package com.cy.core;

import com.cy.http.EmptyRequestException;
import com.cy.http.HttpRequest;
import com.cy.http.HttpResponse;
import com.cy.servlet.HttpServlet;
import com.cy.servlet.LoginServlet;
import com.cy.servlet.RegServlet;
import com.cy.servlet.ShowAllUserServlet;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class ClientHandler implements Runnable{

    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //1解析请求
            HttpRequest request = new HttpRequest(socket);
            //2处理请求
            HttpResponse response = new HttpResponse(socket);
            //3响应客户端
            String uri = request.getRequestURI();
            String servletName = ServerContext.getServletNameByUri(uri);
            if(servletName!=null) {
                System.out.println("准备反射:"+servletName);
                Class cls = Class.forName(servletName);
                HttpServlet servlet = (HttpServlet)cls.newInstance();
                servlet.service(request, response);
            }else {
                File file = new File("webapps" + uri);
                if (file.exists()) {
                    response.setEntity(file);
                    System.out.println("资源已找到");
                } else {
                    //设置响应正文为404页面
                    response.setStatusCode(404);
                    response.setEntity(new File("webapps/root/404.html"));
                    System.out.println("资源不存在");
                }
            }
            response.flush();
        } catch (EmptyRequestException e){
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
